/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="gis-device-panel">
    <Update ref="updateChild"></Update>
    <EdgeModal ref="edgeModalChild" @onUpdateClick="onUpdateClick" @onExitDetailClick="onExitDetailClick" @handleCloseEdgeModal="handleCloseEdgeModal"></EdgeModal>
    <RoadModel ref="roadModalChild" @onUpdateClick="onUpdateClick" @onDetailClick="onDetailClick"></RoadModel>
  </div>
</template>
<script>
import L from 'leaflet'
import { GetAllDevice, getDeviceRange } from '../../../../api/device'
import Update from './update'
import EdgeModal from './edgeModal'
import RoadModel from './roadModel'
import { getMessageByCode } from '../../../../utils/responseMessage'
// import PhaseMarkerVue from './index'
export default {
  name: 'device',
  components: { Update, EdgeModal, RoadModel },
  watch: {
  },
  data () {
    return {
      markerOptions: {
        zIndexOffset: 99999
      },
      map: null,
      lngLat: {
        lng: '0.00000000',
        lat: '0.00000000'
      },
      messageboxVisible: false,
      curDevice: undefined, // 当前所选设备信息
      deviceFaultIcon: require('../../../../assets/gis/devicefault.png'),
      // @ts-ignore
      deviceOnlineIcon: require('../../../../assets/gis/首页在线.svg'),
      // @ts-ignore
      deviceNotOnlineIcon: require('../../../../assets/gis/离线.svg'),
      // @ts-ignore
      deviceYellowFlashIcon: require('../../../../assets/gis/黄闪.svg'),
      // @ts-ignore
      deviceRedIcon: require('../../../../assets/gis/全红.svg'),
      // @ts-ignore
      deviceOfflightIcon: require('../../../../assets/gis/关灯.svg'),
      // @ts-ignore
      deviceFixedIcon: require('../../../../assets/gis/首页定周期.svg'),
      // @ts-ignore
      deviceCoordinateIcon: require('../../../../assets/gis/干线协调.svg'),
      // @ts-ignore
      deviceInterruptIcon: require('../../../../assets/gis/实时干预.svg'),
      deviceLayer: null,
      devList: [],
      isEdgeModalTop: false, // 是否大弹窗置顶
      searchfilter: ''
    }
  },
  mounted () {
    let _this = this
    this.$nextTick(() => {
      _this.getDeviceRanges()
    })
  },
  destroyed () {
    this.hideLayer()
  },
  methods: {
    getDeviceRanges () {
      // 按搜索条件查询路口信息
      let reqData = {
        'pageNum': 1,
        'pageRow': 10000,
        'search': this.searchfilter,
        'type': '',
        'platform': '',
        'protocol': '',
        'state': '',
        'code': '',
        'control': -1,
        'mode': -1,
        'tags': ''
      }
      return getDeviceRange(reqData).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        if (res.data.data.content) {
          this.devList = res.data.data.content
        } else {
          this.devList = []
        }
        this.map = window.map
        this.handleMapDevice(this.devList)
        return this.devList
      })
    },
    getAllAdevice () {
      GetAllDevice().then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.devList = res.data.data
        this.map = window.map
        this.handleMapDevice(this.devList)
      })
    },
    handleMapDevice (devs) {
      if (this.deviceLayer) {
        this.deviceLayer.clearLayers()
      }
      let markers = []
      for (let dev of devs) {
        if (!dev.geometry || !dev.geometry.coordinates || dev.geometry.coordinates.length === 0 || dev.geometry.coordinates[0] === 0) {
          continue
        }
        let coordinates = dev.geometry.coordinates
        let devPoint = [coordinates[1], coordinates[0]]
        let iconUrl = this.deviceFaultIcon
        if (dev.state === 'UP') {
          iconUrl = this.deviceOnlineIcon
          switch (dev.control) {
            case 1:
              iconUrl = this.deviceYellowFlashIcon
              break
            case 2:
              iconUrl = this.deviceRedIcon
              break
            case 3:
              iconUrl = this.deviceOfflightIcon
              break
            case 5:
              iconUrl = this.deviceFixedIcon
              break
            case 10:
              iconUrl = this.deviceCoordinateIcon
              break
            default:
              iconUrl = this.deviceOnlineIcon
              break
          }
          if (dev.mode && dev.mode !== 0) {
            iconUrl = this.deviceInterruptIcon
          }
        } else if (dev.state === 'DOWN') {
          iconUrl = this.deviceNotOnlineIcon
        }
        let notOnlineIcon = L.icon({
          iconUrl: iconUrl,
          iconSize: [42, 31],
          title: dev.state,
          alt: dev,
          iconAnchor: [12, 27]
        })
        let marker = L.marker(devPoint, { icon: notOnlineIcon }).on('click', this.onMarkerClick).on('mouseover', e => {
          // 添加文字的方法
          var html = this.getPopupContent(dev)
          // 鼠标移入弹窗
          marker.bindPopup(html).openPopup()
        })
          .on('mouseout', e => {
            marker.closePopup()
          })
        // 添加marker来设置点击事件
        markers.push(marker)
      }
      this.deviceLayer = L.layerGroup(markers)
      this.map.addLayer(this.deviceLayer)
      this.addMessage()
    },
    handleLook (row) {
      const dev = row
      let edgeModalChild = this.$refs.edgeModalChild
      edgeModalChild.openEdge(dev, true)
    },
    onMarkerClick (e) {
      let dev = e.target.options.icon.options.alt
      let row = this.devList.filter(item => item.id === dev.id)[0]
      // if (this.isEdgeModalTop) {
      //   this.onDetailClick(row)
      // } else {
      //   let roadModalChild = this.$refs.roadModalChild
      //   roadModalChild.openEdge(row)
      // }
      let edgeModalChild = this.$refs.edgeModalChild
      edgeModalChild.openEdge(row, true)

      // this.setCurrent(row)
    },
    addMessage () {
      let _this = this
      this.deviceLayer.eachLayer(function (layer) {
        let options = layer.options.icon.options
        let devData = options.alt
        let content = _this.getPopupContent(devData)
        layer.bindPopup(content)
      })
    },
    getMode (row) {
      if (row.control === 0) {
        return {
          label: this.$t('openatccomponents.overview.modelList0'),
          type: 'success'
        }
      } else if (row.control === 1) {
        return {
          label: this.$t('openatccomponents.overview.modelList1'),
          type: 'warning'
        }
      } else if (row.control === 2) {
        return {
          label: this.$t('openatccomponents.overview.modelList2'),
          type: 'warning'
        }
      } else if (row.control === 3) {
        return {
          label: this.$t('openatccomponents.overview.modelList3'),
          type: 'warning'
        }
      } else if (row.control === 4) {
        return {
          label: this.$t('openatccomponents.overview.modelList4'),
          type: 'warning'
        }
      } else if (row.control === 22) {
        return {
          label: this.$t('openatccomponents.overview.modelList22'),
          type: 'warning'
        }
      } else if (row.control === 5) {
        return {
          label: this.$t('openatccomponents.overview.modelList5'),
          type: 'success'
        }
      } else if (row.control === 6) {
        return {
          label: this.$t('openatccomponents.overview.modelList6'),
          type: 'success'
        }
      } else if (row.control === 7) {
        return {
          label: this.$t('openatccomponents.overview.modelList7'),
          type: 'success'
        }
      } else if (row.control === 8) {
        return {
          label: this.$t('openatccomponents.overview.modelList8'),
          type: 'success'
        }
      } else if (row.control === 9) {
        return {
          label: this.$t('openatccomponents.overview.modelList9'),
          type: 'success'
        }
      } else if (row.control === 10) {
        return {
          label: this.$t('openatccomponents.overview.modelList10'),
          type: 'success'
        }
      } else if (row.control === 11) {
        return {
          label: this.$t('openatccomponents.overview.modelList11'),
          type: 'success'
        }
      } else if (row.control === 12) {
        return {
          label: this.$t('openatccomponents.overview.modelList12'),
          type: 'success'
        }
      } else if (row.control === 13) {
        return {
          label: this.$t('openatccomponents.overview.modelList13'),
          type: 'success'
        }
      } else if (row.control === 14) {
        return {
          label: this.$t('openatccomponents.overview.modelList14'),
          type: 'success'
        }
      } else if (row.control === 15) {
        return {
          label: this.$t('openatccomponents.overview.modelList15'),
          type: 'success'
        }
      } else if (row.control === 16) {
        return {
          label: this.$t('openatccomponents.overview.modelList16'),
          type: 'success'
        }
      } else if (row.control === 17) {
        return {
          label: this.$t('openatccomponents.overview.modelList17'),
          type: 'success'
        }
      } else if (row.control === 18) {
        return {
          label: this.$t('openatccomponents.overview.modelList18'),
          type: 'success'
        }
      } else if (row.control === 19) {
        return {
          label: this.$t('openatccomponents.overview.modelList19'),
          type: 'success'
        }
      } else if (row.control === 21) {
        return {
          label: this.$t('openatccomponents.overview.modelList21'),
          type: 'success'
        }
      } else if (row.control === 23) {
        return {
          label: this.$t('openatccomponents.overview.modelList23'),
          type: 'success'
        }
      } else if (row.control === 24) {
        return {
          label: this.$t('openatccomponents.overview.modelList24'),
          type: 'success'
        }
      } else if (row.control === 99) {
        return {
          label: this.$t('openatccomponents.overview.modelList25'),
          type: 'success'
        }
      } else if (row.control === 100) {
        return {
          label: this.$t('openatccomponents.overview.modelList100'),
          type: 'success'
        }
      } else if (!row.control) {
        return {
          label: '',
          type: ''
        }
      }
    },
    getPopupContent (devData) {
      // let agentid = devData.agentid
      let crossRoadName = devData.name
      // let control = this.getMode(devData).label
      let date = devData.lastTime
      let control = devData.control
      let content =
      `
      <div class="homegis-popup">
        <div class="crossname">${crossRoadName}</div>
      `
      let statusstr = ''
      content = content + statusstr + `<div class="date"><span>${date}</span></div>`
      let status = this.$t('openatc.devicemanager.online')
      if (devData.state === 'UP') {
        status = this.$t('openatc.devicemanager.online')
        let className = 'online-status'
        if (control) {
          status = this.$t('openatccomponents.overview.modelList' + control)
          className = 'online-status online-control' + control
        }
        if (devData.mode && devData.mode !== 0) {
          className = 'online-status online-control-interrupt'
        }
        statusstr = `<div class="content-row"><span class="${className}">${status}</span></div>`
      } else if (devData.state === 'DOWN') {
        status = this.$t('openatc.devicemanager.offline')
        statusstr = `<div class="content-row"><span class="offline-status">${status}</span></div>`
      } else {
        status = this.$t('openatc.devicemanager.fault')
        statusstr = `<div class="content-row"><span class="fault-status">${status}</span></div>`
      }
      content = content + statusstr
      return content
    },
    setNewLocation (lngLat) {
      this.curDevice.lng = lngLat.lng
      this.curDevice.lat = lngLat.lat
      let updateChild = this.$refs.updateChild
      updateChild.onUpdateClick(this.curDevice, true)
    },
    onLocationClick (row) {
      this.setDeviceLocation(row)
      this.$message.info(this.$t('openatc.gis.chooseLocationInfo'))
    },
    setDeviceLocation () {
      this.editMode = true
      let _this = this
      const body = document.querySelector('#map')
      const originStyle = body.style.cursor
      body.style.cursor = 'crosshair'
      // body.style.cursor = url.parse('./001.ico')
      _this.map.on('click', function (e) {
        _this.lngLat.lng = String(e.latlng.lng)
        _this.lngLat.lat = String(e.latlng.lat)
        _this.setNewLocation(_this.lngLat)
        _this.map.off('click')
        body.style.cursor = originStyle
      })
    },
    onDetailClick (row, showModal) {
      const dev = row
      let edgeModalChild = this.$refs.edgeModalChild
      edgeModalChild.openEdge(dev, showModal)
      if (showModal) {
        this.isEdgeModalTop = true
      }
    },
    onExitDetailClick (dev) {
      this.handleCloseEdgeModal()
      this.handleLook(dev)
    },
    getList (searchfilter) {
      if (searchfilter !== undefined) {
        this.searchfilter = searchfilter
      }
      this.hideLayer(this.deviceLayer)
      this.getDeviceRanges()
    },
    hideLayer () {
      this.map.removeLayer(this.deviceLayer)
    },
    showLayer () {
      this.map.addLayer(this.deviceLayer)
    },
    setCurrentMarker (dev) {
      let marker
      let layers = this.deviceLayer._layers
      for (var x in layers) {
        let layer = layers[x]
        if (layer.options.icon.options.alt.id === dev.id) {
          marker = layer
          break
        }
      }
      if (marker) {
        let _latlng = marker._latlng
        this.map.flyTo(_latlng)
        marker.openPopup(_latlng)
      }
    },
    onRowClick (row) {
      this.setCurrentMarker(row)
    },
    onUpdateClick (curDevice) {
      let updateChild = this.$refs.updateChild
      updateChild.onUpdateClick(curDevice, true)
    },
    handleCloseEdgeModal () {
      this.isEdgeModalTop = false
    }
  }
}
</script>
<style lang="scss" scoped>
  .devicePanel /deep/ .active {
    position: static;
  }
</style>
